package bold.shiro;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.Serializable;

/**
 * shiro 测试入口
 *
 * @date 2020/3/3
 * @auther likailun
 **/
@RestController
@Slf4j
public class ShiroController {

    private String CACHE = "cache";

    @RequestMapping("login")
    @ResponseBody
    public Object shiroLogin() {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken("admin", "");
        subject.login(token);
        log.info("登陆成功token={},subject={}", token.toString(), subject.toString());

        Session session = subject.getSession(false);
        ShiroCache shiroCache = new ShiroCache("小明", 15, "123123123213");
        session.setAttribute(CACHE, shiroCache);
        return session.getId();
    }

    /**
     * 自定义存储对象
     */
    @Data
    @ToString
    @AllArgsConstructor
    @NoArgsConstructor
    public static class ShiroCache implements Serializable {
        private String name;
        private Integer age;
        private String phone;
    }

    @RequestMapping("loginOut")
    @ResponseBody
    public Object loginOut() {
        Subject subject = SecurityUtils.getSubject();
        if (subject.getSession(false) != null) {
            subject.logout();
            log.info("退出成功1,subject={}", subject);
        } else {
            log.info("退出成功2,subject={}", subject);
        }
        return "loginOut";
    }

    @RequestMapping("no")
    @RequiresPermissions("no")
    public Object no() {
        System.err.println("访问没权限接口");
        return "没权限 no";
    }

    @RequestMapping("perm1")
    @RequiresPermissions("perm1")
    public String perm1() {
        Object attribute = SecurityUtils.getSubject().getSession(false).getAttribute(CACHE);
        log.info("attribute={}", attribute);
        return "perm1";
    }

    @RequestMapping("perm2")
    @RequiresPermissions("perm2")
    public String perm2() {
        return "perm2";
    }


}
